console.log("Testing all admin APIs...");
const http = require('http');

const testUrls = [
    { path: '/api/v1/admin/user/login', name: '接口1: 用户登录', method: 'POST', data: 'username=admin&password=123456' },
    { path: '/api/v1/admin/category/list', name: '接口5: 所有文章类别', method: 'GET', requireAuth: true },
    { path: '/api/v1/admin/article/query', name: '接口10: 文章搜索', method: 'GET', requireAuth: true },
    { path: '/api/v1/admin/data/info', name: '接口15: 获取统计数据', method: 'GET', requireAuth: true }
];

let authToken = null;

async function testInterface(url, name, method = 'GET', data = null, requireAuth = false) {
    return new Promise((resolve, reject) => {
        const options = {
            hostname: 'localhost',
            port: 8000,
            path: url,
            method: method,
            headers: {
                'Content-Type': method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json'
            }
        };

        if (requireAuth && authToken) {
            options.headers['Authorization'] = `Bearer ${authToken}`;
        }

        if (data && method === 'POST') {
            options.headers['Content-Length'] = Buffer.byteLength(data);
        }

        const req = http.request(options, (res) => {
            let responseData = '';
            res.on('data', (chunk) => {
                responseData += chunk;
            });
            res.on('end', () => {
                try {
                    const jsonData = JSON.parse(responseData);
                    resolve({ name, path: url, status: res.statusCode, data: jsonData });
                } catch (e) {
                    resolve({ name, path: url, status: res.statusCode, data: responseData });
                }
            });
        });

        req.on('error', (e) => {
            reject({ name, path: url, error: e.message });
        });

        req.setTimeout(5000, () => {
            req.destroy();
            reject({ name, path: url, error: 'Timeout' });
        });

        if (data && method === 'POST') {
            req.write(data);
        }

        req.end();
    });
}

async function runTests() {
    console.log('开始测试所有后台接口...\n');
    
    // 首先测试登录接口
    try {
        const loginResult = await testInterface('/api/v1/admin/user/login', '接口1: 用户登录', 'POST', 'username=admin&password=123456');
        console.log(`✓ ${loginResult.name}`);
        console.log(`  Status: ${loginResult.status}`);
        if (loginResult.data && loginResult.data.token) {
            authToken = loginResult.data.token;
            console.log(`  Token获取成功: ${authToken.substring(0, 20)}...`);
        }
        console.log('');
    } catch (error) {
        console.log(`✗ 登录失败: ${error.error}`);
        console.log('');
    }
    
    // 测试其他需要认证的接口
    for (const urlInfo of testUrls.slice(1)) {
        try {
            const result = await testInterface(urlInfo.path, urlInfo.name, urlInfo.method, urlInfo.data, urlInfo.requireAuth);
            console.log(`✓ ${result.name}`);
            console.log(`  URL: ${result.path}`);
            console.log(`  Status: ${result.status}`);
            if (result.data && typeof result.data === 'object') {
                console.log(`  Response fields: ${Object.keys(result.data).join(', ')}`);
                if (result.data.data && Array.isArray(result.data.data)) {
                    console.log(`  Data count: ${result.data.data.length}`);
                }
            }
        } catch (error) {
            console.log(`✗ ${error.name}`);
            console.log(`  URL: ${error.path}`);
            console.log(`  Error: ${error.error}`);
        }
        console.log('');
    }
    
    process.exit(0);
}

runTests().catch(console.error);
